<template>
  <div class="flex justify-center index overauto"
       style="width: 100vw;height: 100vh;overflow-x: hidden;" v-if="props.isPlaceAnOrder">
    <div class="content">
      <div class="relative">
        <div class="back-title" style="background: url(https://img.alicdn.com/imgextra/i1/1034622205/O1CN01CvokW71S9wPCI4Hb5_!!1034622205.png) no-repeat no-repeat center center;
        background-size: cover;">
          <div class="relative back-box">
            <div class="absolute pt-2 pl-4 back-icon " @click="goBack">
              <el-icon><ArrowLeftBold size="16" /></el-icon>
            </div>
            <div class="back-title-text text-[16PX] text-center pt-[6PX]">
              <p >{{getLanguage(props.product.language).confirmOrder}}</p>
              <div class="flex justify-center">
                <p class="flex items-center mr-2">
                  <img class="w-[6PX] h-[6PX]" src="https://img.alicdn.com/imgextra/i3/1034622205/O1CN012HXDiI1S9wPDAGyuZ_!!1034622205.png" alt=""/>
                  <span >{{getLanguage(props.product.language).arrivedPay}}</span>
                </p>
                <p class="flex items-center mr-2" >
                  <img src="https://img.alicdn.com/imgextra/i3/1034622205/O1CN012HXDiI1S9wPDAGyuZ_!!1034622205.png" alt=""/>
                  <span>{{getLanguage(props.product.language).takeProduct}}</span>
                </p>
                <p class="flex items-center mr-2">
                  <img src="https://img.alicdn.com/imgextra/i3/1034622205/O1CN012HXDiI1S9wPDAGyuZ_!!1034622205.png" alt=""/>
                  <span>{{getLanguage(props.product.language).hsinchuBlackCatDelivery}}</span>
                </p>
              </div>
            </div>
            <div class="flex items-center back-title-price w-100% overflow-hidden">
              <div class="flex items-center w-100%">
                  <img class="w-[62PX] h-[62PX] rounded-[20PX]" :src="product?.cover" alt=""/>
                  <div class="ml-4 w-100%">
                    <p class="text-[14PX] w-90%">{{product?.titleExternal}}</p>
                    <div class="flex items-center">
                      <div class=" text-[#FF0C06] mr-[14px] flex items-center">
                        <div class="symbol text-[#FF0C06] text-[12PX]">{{ areaInfo.currencySymbol }}</div>
                        <div class=" text-[#FF0C06] text-bold text-[18PX]">{{ thalis[activeIndex].discountedPrice || 0 }}</div>
                      </div>
                      <div class="text-[#C7C7C7] text-[12PX]" style="text-decoration: line-through">
                        {{getLanguage(props.product.language).originPrice}}：{{ areaInfo.currencySymbol }}{{ thalis[activeIndex].originalPrice || 0 }}
                      </div>
                    </div>
                  </div>
              </div>
            </div>
          </div>
          
          <div class="detailPart">
          </div>
        </div>

        <div class="back-title-model  w-100%">
          <div class="flex items-center w-100% p-2" v-if="product.thaliFlag==1">
              <div class="flex items-center w-100% justify-between">
                <p class="text-[14PX] text-ellipsis">{{getLanguage(props.product.language).model}}</p>
                <div class="flex items-center text-[12PX] text-[#C7C7C7]">{{getLanguage(props.product.language).total}} 
                  <span class="text-[#333]"> {{thalis?.length}} </span> {{getLanguage(props.product.language).modelOptionsAvailable}}</div>
              </div>
          </div>
          <div class="flex items-center w-100% p-2 title-model-item flex-wrap" v-if="product.thaliFlag==1">

            <div class="title-model-btn" v-for="(itm,index) in thalis" :key="index"  
            :class="{ 'active': index == activeIndex}" @click="handleModelClick(itm,index)">
              <p> {{itm?.name}}-{{getLanguage(props.product.language).onlyNeeded}} - {{ areaInfo.currencySymbol }} {{itm.discountedPrice}} <br/></p>
            </div>
             
          </div>
        </div>
        <div class="color-class px-[16px] mt-[30PX]" v-if="!isNaN(computePrice.discountPrice)">
            <!-- <div class=" w-100% p-2">
              <div class="flex items-center w-100% justify-between">
                <p class="text-[16PX]">颜色分类</p>
              </div>
            </div> -->
            <div class="detailPart" >
              <div class="px-[18px]">
                <!-- 套餐商品列表 -->
                <div v-for="(items,indexs) in thaliDetailList" :key="indexs">
                  <div class="mt-4 select-model" v-if="product.thaliFlag==1">
                    <div  class="flex items-center">
                      第{{indexs+1}}件 已选 
                      <p v-if="items.independenceFlag ==1">
                        （<span class="text-[#FD4442]">{{ items.selectSku.map((itm)=>itm.nameForeign).length }}</span>
                        /{{items.specs.length}}）：{{items.selectSku.length>0?items.selectSku.map((itm)=>itm.nameForeign).join('、'):''}}
                      </p>
                      <p v-else>* {{ items.number }}</p>

                    </div>
                  </div>
                  <!-- <div class="mt-2 ml-2" v-if="items.independenceFlag != 1 && thalis.length>0">
                    <div class="text-center w-200px h-100%">
                      <p><img class="w-200px h-200px " :src="items.cover"/></p>
                      <p>{{ items.titleExternal }}</p>
                    
                    </div>
                  </div> -->
                  <div class="flex flex-wrap">

                    <div class="sku mt-[20PX]"
                         v-for="(item,index) in items.specs"
                         :key="index"
                    > 
                      <div>{{ item.nameForeign }}：</div>
                      <el-scrollbar>
                        <div class="list flex flex-wrap mt-[15PX]">
                          <div
                            v-for="(it,idx) in item.list"
                            :key="idx"
                            @click="handleBtnClick({type:'sku',index,idx,item,it,indexs})"
                            class="mt-[10PX]"
                          >
                            <div
                              class="px-[5PX] py-[5PX] rounded-[8PX] mr-[18PX] transition"
        
                              :class="`${idx+1 == item.selected ? 'bg-[#FD4442]' : 'bg-[#F5F5F5]' }`"
                            >
                            <div class="flex items-center">
                              <div class="w-[52PX] h-[52PX] rounded-[8PX] bg-[#fff]" v-if="it.url">
                                <img class="w-[52PX] h-[52PX] rounded-[8PX]" :src="it.url" alt=""/>
                              </div>
        
                              <div class="ml-[10PX] mr-[10PX] flex-center min-w-20PX"
                                   :class="`${ idx+1 == item.selected ?  'text-[#fff]' : '' }`">
                                {{ it.nameForeign }}
                              </div>
      
                            </div>
      
                            </div>
                          </div>
        
                        </div>
                      </el-scrollbar>
                    </div>
                  </div>
                  <div class="sku mt-[20PX]" v-if="props.product.thaliFlag == 0">
                    <div>{{getLanguage(props.product.language).number}}</div>
                    <div class="mt-[15PX]">
                      <el-input-number v-model="form.number"/>
                    </div>
                  </div>
                </div>
  
            </div>
  
  
          </div>
        </div>
        


        <div class="lint mt-[15PX]" style="border-top: dashed 1px #F5F5F5">

        </div>

         <div class="px-[16PX] mt-[14PX] pb-[65PX] block" v-if="!isNaN(computePrice.discountPrice)">
          <div class="px-[16PX] py-[14PX] bg-[#fff] rounded-[12PX]" >
            <div class="flex items-center justify-between">
              <div class="text-[14PX] label">{{getLanguage(props.product.language).orderInfo}}：</div>
              <div class="flex items-center val">
                <div class="text-[12PX]  text-[#fff] px-[7PX] py-[4PX] rounded-[13PX] mr-[10PX] yhbtn" v-if="product.discountedPrice" style="background:  linear-gradient( 270deg, #FF3400 0%, #FD4442 100%);">{{getLanguage(props.product.language).havedCoupon}}</div>
                <div class="flex items-baseline">
                  <span class="text-[14PX]  text-[#FF0C06] mr-[4PX]">{{getLanguage(props.product.language).total}}</span>
                  <div class="text-[17PX] text-[#FF0C06] font-bold" v-if="!isNaN(computePrice.discountPrice) ">{{ areaInfo.currencySymbol }}{{  computePrice.discountPrice }}</div>
                </div>
              </div>
            </div>
            <div class="flex justify-between mt-[10PX]  items-center">
              <div class="text-[14PX] label">
                {{getLanguage(props.product.language).productNameTag}}
                <span class="text-[#C7C7C7] text-[12PX]">
                  <!-- ({{getLanguage(props.product.language).total}}{{form.number}}{{getLanguage(props.product.language).numberUnit}}) -->
                </span>
              </div>
              <div class="flex items-center val">
                <div class="flex text-[14PX] text-[#333] items-baseline">
                  {{getLanguage(props.product.language).originPrice}} {{ areaInfo.currencySymbol }} {{ computePrice.price }}
                </div>
              </div>
            </div>
            <!-- 手续费 -->
            <div class="flex justify-between mt-[10PX]  items-center" v-if="product.commission">
              <div class="text-[14PX] label">
                {{getLanguage(props.product.language).commission}}
              </div>
              <div class="flex items-center val">
                <div class="flex text-[14PX] text-[#333] items-baseline">
                 {{ areaInfo.currencySymbol }} {{ product.commission || 0 }}
                </div>
              </div>
            </div>
             <!-- 運费 ---修改 -->
             <div class="flex justify-between mt-[10PX]  items-center" v-if="product.shippingFee">
              <div class="text-[14PX] label">
                {{getLanguage(props.product.language).shippingFee}}
              </div>
              <div class="flex items-center val">
                <div class="flex text-[14PX] text-[#333] items-baseline">
                 {{ areaInfo.currencySymbol }} {{ product.shippingFee || 0 }}
                </div>
              </div>
            </div>
            <!-- 偏遠地區郵费 -->
            <div class="flex justify-between mt-[10PX]  items-center" v-if="product.remotePostage && isRemote">
              <div class="text-[14PX] label">
                {{getLanguage(props.product.language).remotePostage}}
              </div>
              <div class="flex items-center val">
                <div class="flex text-[14PX] text-[#333] items-baseline">
                 {{ areaInfo.currencySymbol }} {{ product.remotePostage || 0 }}
                </div>
              </div>
            </div>
            <!-- 优惠 -->
            <div class="flex justify-between mt-[10PX]  items-center" v-if="product.discountedPrice">
              <div class="text-[14PX] label">
                {{getLanguage(props.product.language).discount}}
              </div>
              <div class="flex items-center val"  @click="handleArrow">
                <div class="flex text-[14PX] text-[#333] mr-[4PX] items-baseline">
                  <!-- -{{ areaInfo.currencySymbol }} {{ computePrice.originalPrice - computePrice.discountPrice || product.originalPrice - computePrice.discountPrice }} -->
                  -{{ areaInfo.currencySymbol }}{{ isPickup? (computePrice.lessPrice + product.couponAmount)  : computePrice.lessPrice}}
                </div>

                <el-icon v-if="showCoupon"><ArrowDown size="16"  /></el-icon>
                <el-icon  v-else  ><ArrowUp size="16"  /></el-icon>
              </div>
            </div>
            <div class="mt-[6PX]" v-if="showCoupon">
              <div class="rounded-[12PX] px-[16PX] py-[6PX] bg-[#FAFAFA]">
                <div class="flex justify-between py-[4PX] items">
                  <div class="label">{{getLanguage(props.product.language).promotion}}</div>
                  <div class="text-[#FF3400] val">
                    -{{ areaInfo.currencySymbol }}{{ computePrice.lessPrice }}
                  </div>
                </div>
                <div class="flex justify-between py-[4PX] items" v-if="isPickup">
                  <div class="label"> {{  getLanguage(props.product.language).coupon}}</div>
                  <div class="val" :class="product.couponAmount?'text-[#FF3400]':'text-[#333]'">
                    
                    {{ product.couponAmount?`-${areaInfo.currencySymbol} ${product.couponAmount}`:  getLanguage(props.product.language).disable }}
                  </div>
                </div>
              </div>
            </div>
            
            <div class="flex justify-between items-end mt-[10PX]">
              <div>{{getLanguage(props.product.language).total1}}</div>
              <div class="flex items-end">
                <div class="mr-[5PX]">{{ areaInfo.currencySymbol }}</div>
                <div class="font-bold text-[18PX] mb-[-5PX]">{{ computePrice.discountPrice }}</div>
              </div>
            </div>
          </div>
        </div>

        <div class="lint mt-[15PX]" style="border-top: dashed 1px #F5F5F5">

        </div>

        <div class="px-[18px] mt-[30PX]">
          <div class="flex">
            <div class="text-[#FF0C06]">*</div>
            {{getLanguage(props.product.language).logisticsMethod}}
          </div>

          <div class="mt-[15PX] flex items-center  flex-wrap overauto w-[100%]">

            <div v-for="(item,index) in logisticsList" :key="index"
                 @click="handleBtnClick({ type:'logistics',index })"
            >
              <div class="w-[190PX] h-[72PX] bg mb-[10PX] mr-[10PX] transition"
                   :style="`background-image:url(${ index == form.activeLogistics ? 'https://img.alicdn.com/imgextra/i1/801089336/O1CN01D42yhk2IpwkNddK1S_!!801089336.png' : 'https://img.alicdn.com/imgextra/i3/801089336/O1CN01JcP79p2IpwkO5pPNf_!!801089336.png' })`"

              >

                <div class="pl-[40PX] pt-[15PX] flex items-center">
                  <div class="w-[18PX] h-[18PX] bg mr-[5PX]"
                       :style="`background-image:url(${ item.logo })`"></div>
                  <div class="text-[16PX]">
                    {{ item.methodName }}
                  </div>
                </div>

                <div class="mt-[10px] text-[#999999] pl-[40PX]">
                  {{ item.title }}
                </div>


              </div>
            </div>

          </div>

          <div  v-if="instruction.id"
            class="mt-[15PX] bg-[#FFF8EE] px-[20PX] py-[20PX] rounded-[8PX] text-[#8D5B0E] flex items-center"
            style="border: solid 1px rgba(141,91,14,0.2)">
            <div class="w-[15PX] h-[15PX] bg mr-[10PX]"
                 style="background-image: url(https://img.alicdn.com/imgextra/i2/801089336/O1CN01FXSiiT2IpwkHYqnkr_!!801089336.png)"></div>
           {{ instruction.stateInstructions }}

          </div>

        </div>


        <div class="lint mt-[15PX]" style="border-top: dashed 1px #F5F5F5">

        </div>

        <div class="px-[18px] mt-[30PX]">
          <div class="flex">
            <div class="text-[#FF0C06]">*</div>
            {{getLanguage(props.product.language).payMethod}}
          </div>

          <div class="mt-[15PX] flex items-center">
            <div class="w-[16PX] h-[16PX] bg mr-[5PX]"
                 style="background-image: url(https://img.alicdn.com/imgextra/i4/801089336/O1CN01SdoNZU2IpwkN2ooAs_!!801089336.png)"></div>
            {{getLanguage(props.product.language).arrivedPay}}
          </div>

        </div>

        <div class="lint mt-[15PX]" style="border-top: dashed 1px #F5F5F5">

        </div>


        <div class="px-[18px] mt-[30PX] pb-[65PX] " v-if="!isNaN(computePrice.discountPrice) ">
          <div class="flex">
            {{ getLanguage(props.product.language).sendMethod }}
          </div>


          <div class="mt-[15px] templateForm">
            <el-form :model="form" :rules="rules" ref="formRef">

              <el-row :gutter="24">
                <el-col :xs="item.xs"
                        :xl="item.xl"
                        :lg="item.xl"
                        v-for="(item,index) in inputConfig"
                        :key="index"

                >

                  <el-form-item :prop="item.code"
                                v-if="((item.directly && logisticsList[form.activeLogistics]?.directlyStatus == 0) || !item.directly) ? true : false "
                  >

                    <el-input v-model="form[item.code]"
                              :placeholder="item.name"
                              :min="0"
                              v-if="!item.type || item.type == 'text'"
                              :disabled="(item.code == 'detailAddress' ? (logisticsList[form.activeLogistics]?.directlyStatus == 0 ? true  :false)  : false) "
                    />
                    <el-select v-model="form[item.code]"
                               :placeholder="item.name"
                               v-if="item.type == 'select'"
                               @change="onChange(item.code)"
                    >

                      <el-option v-for="(it,idx) in item.list" :key="idx" :value="it[item.value]"
                                 :label="it[item.label]"/>

                    </el-select>

                    <el-input
                      :placeholder="item.name" v-model="form[item.code]"
                      v-if="item.type == 'textarea'"
                      type="textarea"
                      :rows="5"
                      resize="none"
                    />

                  </el-form-item>
                </el-col>
              </el-row>

            </el-form>
          </div>


        </div>
          <div>
            <Policy :policy-list="policyList"/>
          </div>

        <div v-if="!isNaN(computePrice.discountPrice) " class="fixed left-[50%] translate-x-[-50%] bottom-0  z-10  w-[100%] max-w-[640PX]  h-[45PX] flex-center bg-[#FF0C06] text-[#FFF]"
             @click="handleBtnClick({type:'submit'})"> {{getLanguage(props.product.language).submit}}
        </div>
        <div v-else class="fixed left-[50%] translate-x-[-50%] bottom-0  z-10  w-[100%] max-w-[640PX]  h-[45PX] flex-center bg-[#ccc] text-[#FFF]"
            > {{getLanguage(props.product.language).undisabled}}
        </div>
        

      </div>
    </div>
  </div>

</template>
<script lang="ts" setup>
import { getLanguage } from "@/utils/langue";
import {useMessage} from "@/hooks/web/useMessage";
import { ArrowLeftBold } from '@element-plus/icons-vue'
import { computeSkuData, deepCopy } from "@/utils/index";
import { ArrowDown } from '@element-plus/icons-vue'
import { ArrowUp } from '@element-plus/icons-vue'
import Policy from "../components/policy.vue";

const message = useMessage();
const props = defineProps({
  instruction:{
    type: Object,
    required: false,
    default: () => {
    }
  },
   remoteList: {
    type: Array,
    required: false,
    default: () => []
  },
    policyList: {
    type: Array,
    required: false,
    default: () => []
  },
  hasProvince:{
    type: Boolean,
    default:true,
  },
  packageList: {
    type: Array,
    required: false,
    default: () => []
  },
  isPlaceAnOrder: {
    type: Boolean,
    default: false
  },
  product: {
    type: Object,
    required: false,
    default: () => {
    }
  },
  areaInfo: {
    type: Object,
    required: false,
    default: () => {
    }
  },
  skuInfo: {
    type: Array,
    required: false,
    default: () => []
  },
  //原商品列表sku
  originalSku: {
    type: Array,
    required: false,
    default: () => []
  },
  provinceList: {
    type: Array,
    required: false,
    default: () => []
  },
  logisticsList: {
    type: Array,
    required: false,
    default: () => []
  },
  storeList: {
    type: Array,
    required: false,
    default: () => []
  },
  globalConfig:{
    type: Object,
    required: false,
    default: () => {}
  },
  isPickup:{
    type:Boolean,
    required:false,
    default:()=>false
  }
});

const formRef = ref(null)
const isRemote = ref(false)
const policyLists= ref([])
const emit = defineEmits(['confirm', 'execute','update:isPlaceAnOrder']);
const isShow = ref(false)
const originalSkus = ref([])
const activeIndex = ref(0)
const thalis = ref(props.product?.thalis.filter(res => res.saleFlag == 1)) //套餐列表
const thaliDetailList = ref([]) //当前套餐下的商品列表
const modelList = ref([])
const config = ref([
  {
    name: "免运费",
  },
  {
    name: "货到付款",
  },
  {
    name: "15天鉴赏期",
  },
  {
    name: "正品保证",
  }
])


const skuList = ref([])

const initConfig = [
  {
    name: "姓名",
    code: "customerName",
    xs: 24,
    xl: 24,
    required: true
  },
  {
    name: "手机",
    code: "customerPhone",
    xs: 24,
    xl: 24,
    required: true
  },
 {
    name: "地區",
    code: "areaName",
    type: "select",
    label: "name",
    value: "value",
    xs: 24,
    xl: 8,
    required: true,
    show:true,
    list:[
      {
        name: props.product.areaName,
        value: props.product.areaName
      }
    ]
  },
  {
    name: "选择省",
    code: "cityName",
    type: "select",
    label: "name",
    value: "name",
    xs: 24,
    xl: 8,
    required: true,
    show:props.hasProvince,
  },
  {
    name: "选择市区",
    code: "regionName",
    type: "select",
    label: "name",
    value: "name",
    xs: 24,
    xl: 8,
    required: true,
    show:props.hasProvince,
  },
  // {
  //   name: "选择地区",
  //   code: "regionName",
  //   type: "select",
  //   label: "name",
  //   value: "id",
  //   xs: 24,
  //   xl: 8,
  //   required: true,
  //   show:props.hasProvince,
  // },
  {
    name: "选择门店",
    code: "addressId",
    type: "select",
    label: "name",
    value: "id",
    xs: 24,
    xl: 24,
    required: false,
    directly: true,
  },
  {
    name: "详细地址",
    code: "detailAddress",
    xs: 24,
    xl: 24,
    required: true
  },
  {
    name: "留言",
    code: "message",
    type: "textarea",
    xs: 24,
    xl: 24,
    required: false
  }
]

const inputConfig = ref([...initConfig]);
console.log(props.product, "props.product666");

const computePrice = computed(() => {
  //获取sku列表
  //查看是否全部选中
  let isAllSelected = isAllPropertySelected().isAllSelected
  
  if (isAllSelected) {
    
      let selectArr =  isAllPropertySelected().selectedItem;
      let totalOriginalPrice = 0;
      let totalDiscountPrice = 0;
      
      console.log(selectArr,'selectArrselectArr');
      if(props.product.thaliFlag != 1){
        selectArr.forEach(item=>{          
         totalOriginalPrice+=item?.price * parseInt(form.value.number);
         totalDiscountPrice+= item?.discountedPrice * parseInt(form.value.number);
        })
      }else{
        totalOriginalPrice= Number(props.product.thalis[activeIndex.value].originalPrice);
        totalDiscountPrice = Number(props.product.thalis[activeIndex.value].discountedPrice);
      }
      if(!totalDiscountPrice) totalDiscountPrice = totalOriginalPrice
      if (props.product.couponAmount && props.isPickup) {
        totalDiscountPrice -= (props.product.couponAmount || 0)
      }
    return {
      price:totalOriginalPrice.toFixed(2),//原价
      discountPrice:
      (totalDiscountPrice + ( isRemote.value? (props.product.remotePostage ||0) : 0 ) +  (props.product.shippingFee || 0) +(props.product.commission || 0)).toFixed(2),//折扣价
      remotePostage:(isRemote.value? (props.product.remotePostage||0) : 0).toFixed(2),//远程费
      shippingFee: (parseFloat(thalis.value[activeIndex.value]?.shippingFee) > 0 ?parseFloat(thalis.value[activeIndex.value]?.shippingFee): props.product.shippingFee || 0).toFixed(2),//运费
      commission:(props.product.commission||0).toFixed(2),//佣金
      lessPrice: (totalOriginalPrice - totalDiscountPrice).toFixed(2),//优惠价格
    }

  } else {
    let totalDiscountFlagPrice = 0;
    totalDiscountFlagPrice = parseFloat(thalis.value[activeIndex.value]?.discountedPrice)>0 ? thalis.value[activeIndex.value]?.discountedPrice : props.product.discountedPrice
    return {
      price:props.product.originalPrice.toFixed(2),//原价
      discountPrice:(totalDiscountFlagPrice - (props.isPickup ? (props.product.couponAmount || 0) : 0) ).toFixed(2),//折扣价
      remotePostage:(isRemote.value? (props.product.remotePostage||0) : 0).toFixed(2),//远程费
     shippingFee:(props.product.shippingFee || 0).toFixed(2),//运费
      commission:(props.product.commission||0).toFixed(2),//佣金
      lessPrice: (props.product.originalPrice - (props.product.discountedPrice || 0)).toFixed(2),//优惠价格
    }
    
  }
})
const handleChange = (val) => {
  console.log(val)
}
const show = () => {
  isShow.value = true
}
const goBack = () => {
  emit('update:isPlaceAnOrder', false)
}
const handleModelClick  = (item,index) => {
   activeIndex.value = index;
   let newselthaliDetailList = deepCopy(thalis.value[index].thaliDetailList)
   newselthaliDetailList.map(res => {
      let spes = deepCopy(res.specs)
      res.specs = computeSkuData(deepCopy(spes))
      res.oldSpecs = deepCopy(spes)
   })
   thaliDetailList.value = newselthaliDetailList
   thaliDetailList.value.map(item => {
     item.selectSku = []
   })
  // emit('execute',item)
  // console.log(thalis.value[index].thaliDetailList,'thaliDetailList');
  
}
/**
 * 计算rules
 * */
const rules = computed(() => {

  let obj = {}
  inputConfig.value.forEach(item => {
    if (item.required) {
      obj[item.code] = [{
        required: true,
        message: `请${item.type == 'select' ? '选择' : '输入'}${item.name}`,
        trigger: `${item.type == 'select' ? 'change' : 'blur'}`
      }]
    }

  })

  console.log(obj, "===")
  return obj
})

let initForm = {
  number: 1,
  activeLogistics: 0
}

const form = ref({
  ...initForm
})
// const selectSku = ref([])
const handleBtnClick = (e) => {
  let type = e.type;
  try {
    fn[type](e)
    if(type == 'logistics'){
    // 清空省市区
    form.value.area = null
    form.value.areaName =null
    form.value.cityName =null
    form.value.addressId =null
  }
  } catch (e) {
    console.log(`${type}不存在`)
  }
}

const isAllPropertySelected = () => {
  let selectedItem =  []
  let isAllSelected= true;

  let productList = deepCopy( thaliDetailList.value || []);
  console.log(productList, "productList")

  productList.forEach((item) => {
    console.log(item.independenceFlag,"skuList[i].independenceFlag");
    let skuList = item.specs || [];
    for(let i=0;i<skuList.length;i++){
      if(item.independenceFlag==1){
        if(!skuList[i].selected){
          isAllSelected=false;
          break;
        }
      }else {
        skuList[i].selected = i + 1;
      }
    }
  })

  if(isAllSelected){
    productList.forEach((item,index) => {
        let skuList = item.specs || [];

        let oldSpes = item.oldSpecs || [];

        let selectedArr = [];
        skuList.forEach(it => {
            selectedArr.push(it.list[it.selected-1])
          })
        let name = selectedArr.map(item=>item.name).join('§');


        let  selectedObj = oldSpes.find(at=>{
          return at.propertyValue == name
        })
        selectedItem.push(selectedObj);
        
    })
  }

  console.log(selectedItem,"selectedItem2")
  return {
    selectedItem,
    isAllSelected
  }
}

const fn = {
  pickupCoupon() {
    if (!isPickup.value) {
      isPickup.value = true;
      message.success("领取成功")
    }
  },
  async submit() {
    try {
      let res = await formRef.value.validate();
   

      //查看有没有v选择sku
      if (isAllPropertySelected().isAllSelected) {

        let addressItem = inputConfig.value.find(at=>{
          return at.code == "addressId"
        })


        let address = null;
        if(addressItem){
          let lis = addressItem.list;

          console.log(lis,"==============")

          if(form.value.addressId){
            address = lis.find(at=>{
              return at.id == form.value.addressId
            })?.name
          }
        }


        emit('execute', {
          type: 'confirm',
          form: form.value,
          address:address,
          skuList: skuList.value,
          priceInfo: computePrice.value,
          isPickup: props.isPickup,
          selectedProperty: isAllPropertySelected().selectedItem,
          thaliId: props.product.thaliFlag == 1 ? thalis.value[activeIndex.value]?.id : '',
          success() {
            if(props.globalConfig.orderDelectSteat == 1){
              form.value = {
                ...initForm
              }
            }

          }
          //其他 sku等信息
        })
      } else {
        message.error("请选择sku");
      }


    } catch (e) {
      console.log(e)
      for (let i in e) {
        message.error(e[i][0].message);
        return
      }
    }
  },
  logistics({index}) {
    form.value.activeLogistics = index;
  },
  sku({item, it, index, idx,indexs}) {
    item.selected = idx + 1;
    let newdelList = deepCopy(thaliDetailList.value) //商品列表
     if(newdelList[indexs].selectSku[index]){
        newdelList[indexs].selectSku[index].nameForeign = it.nameForeign
      }else{
        newdelList[indexs].selectSku.push({
          nameForeign:it.nameForeign
        })
      }
      // newdelList[indexs].map(res=>{
      //   res.specs = computeSkuData(res.specs)
      // })
      thaliDetailList.value =  newdelList
  }
}

const onChange = code => {
  if (code == 'areaName') {
    form.value.cityName = ''
    form.value.regionName = ''
    //生成
    let item = inputConfig.value.find(at => {
      return at.code == 'cityName'
    })
    //获取市
    let it = props.provinceList.find(at => {
      return at.name == form.value[code];
    })
    if(item){
      item.list = it.list || [];
    }


    item = inputConfig.value.find(at => {
      return at.code == 'regionName'
    })
    if(item){
      item.list = []
    }

    item = inputConfig.value.find(at => {
      return at.code == 'addressId'
    })
    if(item){
      item.list = [];
    }

  } else if (code == 'cityName') {
    form.value.regionName = ''

    let item = inputConfig.value.find(at => {
      return at.code == 'regionName'
    })

    let item1 = inputConfig.value.find(at => {
      return at.code == 'cityName'
    })

    let it = item1.list.find(at => {
      return at.name == form.value.cityName
    })
    if(item){
      item.list = it.list
    }


    item = inputConfig.value.find(at => {
      return at.code == 'addressId'
    })
    if(item){
      item.list = [];
    }
  } else if (code == 'regionName') {


  } else if (code == 'addressId') {
    let it = props.storeList.find(at => {
      return at.id == form.value[code]
    })

    form.value.detailAddress = it.detailedAddress
  }
}
onMounted(() => {
  policyLists.value = props.policyList?.filter(at=>at.title!='')
})

watch(() => props.provinceList, () => {
  let item = inputConfig.value.find(at => {
    return at.code == 'cityName'
  })
  item.list = props.provinceList
}, {
  deep: true,
  immediate: true
})

watch(() => [form.value.activeLogistics, form.value.regionName], () => {
  if (form.value.regionName) {
    isRemote.value = props.remoteList.find(at => {
      return at.city == form.value.regionName
    })
    if (props.logisticsList[form.value.activeLogistics]?.directlyStatus == 0) {
      //获取store
      emit('execute', {
        type: 'store',
        data: form.value,
        callback(storeList) {
          let item = inputConfig.value.find(at => {
            return at.code == 'addressId'
          })
          item.list = storeList.map(item => {
            return {
              id:item.id,
              name: item.storeName,
              address: item.detailedAddress
            }
          })
        }
      })
    }

  }
}, {
  deep: true,
  immediate: true
})


watch(() => props.product, () => {
  // skuList.value = props.skuInfo;
  let thalis = props.product?.thalis.filter(at=>at.saleFlag == 1)
  let letthaliDetailList= thalis.length>0?deepCopy(thalis[0]?.thaliDetailList):[]
  letthaliDetailList.map(res=>{
      let spes = deepCopy(res.specs)
      res.specs = computeSkuData( deepCopy(spes))
      res.oldSpecs = deepCopy(spes)
  }
  )
  thaliDetailList.value  = letthaliDetailList
  let newthaliDetailList = deepCopy(thaliDetailList.value)
  thaliDetailList.value = newthaliDetailList.map((item,index)=>{
   return {
    ...item,
    selectSku:[]
  }
})
  console.log(skuList.value, "skuList.valueskuList.valueskuList.value")
}, {
  deep: true,
  immediate: true
})
//抛出show
defineExpose({
  show
})
</script>
<style>
</style>
<style scoped lang="less">
.back-title{
  width: 100%;
  height: 166PX;
}
.back-title-text{
  img{
    width: 10PX;
    height: 10PX;
  }
  span,p{
    color: #073064;
    font-size: 14PX;
  }
  span{
    padding-left: 2PX;
  }
}
.back-title-price{
  position: absolute;
  top: 54PX;
  left: 0;right: 0;
  margin: auto;
  // height: 52PX;
  width: 96%;
  border-radius: 11PX;
  background: #fff;
  box-shadow: 0PX 2 3PX 1PX rgba(0,0,0,0.03);
  padding: 10PX;
  box-sizing: border-box
}
.back-title-model{
  margin: -10PX auto;
  width: 100%;
  border-radius: 11PX;
  background: #fff;
  box-shadow: 0PX 2 3PX 1PX rgba(0,0,0,0.03);
  padding: 0 10PX;
  box-sizing: border-box;
  .title-model-item{

    .title-model-btn{
      background: #FFF6F6;
      border-radius: 6PX;
      padding: 6PX 12PX;
      font-weight: 400;
      font-size: 14PX;
      color: #333333;
      text-align: left;
      font-style: normal;
      text-transform: none;
      margin-right: 16PX;
      margin-top: 8PX;
    }
    .title-model-btn.active{
      border: 1PX solid #FF0C06;
      color: #FF0C06;
    }
  }
}
.color-class{
  .select-model{
    background: #FAFAFA;
    border-radius: 6PX;
    padding: 8PX 16PX;
  }
  .select-color-class{
    .select-model-pro{
      .select-model-pro-item{
        padding: 12PX;
        box-sizing: border-box;
        background: #FFFFFF;
        border-radius: 6PX;
        border: 1PX solid #E4E4E4;
          margin-right: 16PX;
        margin-top: 8PX;
      }
      .select-model-pro-item.active{
        border: 1PX solid #FF0C06;
        color: #FF0C06;
        background: #FFF6F6;
      }
    }
  }
}
// 超出省略
.text-ellipsis{
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.policy{
  p{
    font-size: 10PX;
  }
  img{
    width: 9PX;
    height: 9PX;
    border-radius: 50%;
  }
  :deep(.el-collapse-item__header){
     height: 30PX;
    line-height: 30PX;
    font-size: 12PX;
    border: none !important;
  }
}










@import "@/common";

.index {
  .content {
    width: 640PX;
    height: 100%;

    .top-title {
      font-size: 14PX !important;
      .btn-promotion{
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 6PX;
        width: 40PX;
        line-height: 40PX;
        height: 18PX;
        background: #FFF5F5;
        border-radius: 3PX;
        border: 1px solid #FF0C06;
        color: #FF0C06;
        font-size: 12PX;
      }

      .bar {
        width: 4PX;
      }
    }

    .subTitle {
      font-size: 10PX !important;
    }

    .swiper {
      width: 100%;
      height: 640PX;

      .swiper-item {
        width: 100%;
        height: 640PX;
      }

      .benefit {
        width: 100%;
        height: 64PX;

        .qianggou-num {
          padding: 5PX 12PX;
        }
      }

      .cycle {
        width: 27PX;
        height: 27PX;
        border-radius: 5PX;
        background: #FD4442;
      }
    }


    .price {
      font-size: 28PX;
      margin-bottom: -5PX;
    }

    // .coupon {
    //   width: 100%;
    //   height: 45PX;
    //   padding-left: 60PX;
    // }


    .icons {
      width: 14PX;
      height: 14PX;
    }
  }

  .ft12 {
    font-size: 12PX !important;
  }
}

@media screen and (max-width: 640PX) {
  .index {
    .content {
      width: 100%;

      .swiper {
        width: 100vw;
        height: 100vw;

        .swiper-item {
          width: 100vw;
          height: 100vw;
        }
      }
    }

    .ft12 {
      .font(18);
    }

  }
}

:deep(.el-carousel) {
  width: 100%;
  height: 100%;

  .el-carousel__container {
    width: 100%;
    height: 100%;
  }
}

:deep(.el-input-number) {
  width: 135PX;
  height: 30PX;

  .el-input-number__decrease, .el-input-number__increase {
    width: 28PX;
    height: 28PX;
    border-radius: 0PX;
  }

  .el-input__inner, .el-input__wrapper {
    height: 30PX !important;
  }

  .el-icon {
    font-size: 14PX;
  }

}

:deep(.el-input) {
  height: 30PX;

  .el-input__inner, .el-input__wrapper {
    height: 30PX !important;
    border-radius: 5PX;
  }


}

:deep(.el-textarea ) {
  height: 60PX !important;

  .el-textarea__inner {
    height: 60PX !important;
    font-size: 10PX;
  }

}


:deep(.el-select) {
  height: 30PX !important;

  .el-select__selected-item, .el-input__inner, .el-select__wrapper {
    height: 30PX !important;


  }

  .el-select__placeholder {
    display: flex !important;
    align-content: center;
    align-items: center;
  }

}

:deep(.el-form-item) {
  margin-bottom: 0PX;
  margin-top: 15PX;
}
</style>
